<template>
	<view class="gift-list-container">
		<!-- 顶部搜索区域 -->
		<!-- <view class="header-section">
			<view @click="search" class="u-search-box">
				<view class="u-search-inner">
					<u-icon name="search" color="#909399" :size="28"></u-icon>
					<text class="u-search-text">搜索商品</text>
				</view>
			</view>
		</view> -->
		<!-- <view class="search">
			<u-search placeholder="搜索商品" v-model="keywords" @custom="search" @search="search"></u-search>
		</view> -->

		<!-- 列表容器 -->
		<scroll-view
			class="scroll-list"
			scroll-y="true"
			@scrolltolower="loadMore"
			:refresher-enabled="true"
			:refresher-triggered="triggered"
			@refresherrefresh="refresherrefresh"
		>
			<view class="list-content">
				<view
					v-for="(item, index) in giftList"
					v-if="item"
					:key="item.id || index"
					class="gift-item"
					@click="onItemClick(index)"
				>
					<!-- 商品图片 -->
					<view class="item-image" >
						<image
							:src="item.basInv.picUrl || '/static/image/commodity.png'"
							mode="aspectFit"
							class="product-image"
						></image>
					</view>

					<!-- 商品信息 -->
					<view class="item-info" >
						<view class="product-name">{{ item.basInv.cinvname || '' }}</view>
						<view class="product-desc">赠品件数：{{ item.iqty || '' }} {{ item.basInv.csacomunitname || '' }}</view>
						<!-- <view class="product-price">{{ item.amount ? '¥' + item.amount : '' }}</view> -->
					</view>

					<!-- 赠品标签 -->
					<view class="gift-tag">
						<text class="tag-text">赠品</text>
					</view>

					<!-- 分隔线 -->
					<view v-if="index !== giftList.length - 1" class="line-wrapper">
						<view class="line"></view>
					</view>
				</view>
			</view>

			<!-- 加载更多组件 -->
			<u-loadmore :status="loadStatus" @loadmore="loadMore"></u-loadmore>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keywords: '',
				giftList: [],
				loadStatus: 'loadmore', // loadmore, loading, nomore
				triggered: false,
				query: {
					pageNo: 1,
					pageSize: 20
				}
			}
		},
		computed: {
			// 调试用：检查 giftList 的数据状态
			giftListDebug() {
				return {
					length: this.giftList.length,
					hasUndefined: this.giftList.some(item => item === undefined),
					hasNull: this.giftList.some(item => item === null),
					firstItem: this.giftList[0],
					allItems: this.giftList
				}
			}
		},
		onLoad() {
			// 登录人
			this.query.cusCode = this.vuex_basCus.code;
			console.log('页面加载，用户信息:', this.vuex_basCus);
			console.log('请求参数:', this.query);

			// 测试网络连接
			this.testNetworkConnection();

			this.loadGiftList();
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 搜索功能
			search() {
				// 可以跳转到搜索页面或者显示搜索框
				console.log('点击搜索');
				// uni.navigateTo({
				//     url: '/pages/btdm/index/gift/search'
				// });
			},
			
			// 加载礼品列表数据
			loadGiftList(type = 'refresh') {
				console.log('开始加载礼品列表，类型:', type);
				console.log('请求参数:', this.query);

				// 检查 API 方法是否存在
				if (!this.$u.api.shop.viewListData) {
					console.error('API 方法 shopGiftData 不存在');
					this.$u.toast('API 配置错误');
					return;
				}

				// 真实API调用
				this.$u.api.shop.viewListData(this.query)
					.then(res => {
						console.log('API 调用成功，返回结果:', res);

						if (res && res.list && res.list.length > 0) {
							console.log('原始数据:', res.list);
							console.log('原始数据第一项:', res.list[0]);

							// 过滤掉无效的数据项
							const validList = res.list.filter(item => item != null);

							if (type === 'refresh') {
								this.giftList = validList;
							} else if (type === 'loadmore') {
								this.giftList = this.giftList.concat(validList);
							}

							console.log('过滤后的有效列表:', validList);
							console.log('当前 giftList:', this.giftList);

							// 判断是否还有更多数据
							if (res.list.length < this.query.pageSize) {
								this.loadStatus = 'nomore';
							} else {
								this.loadStatus = 'loadmore';
							}
						} else {
							console.log('API 返回数据为空或格式不正确:', res);
							this.loadStatus = 'nomore';

							// 如果没有数据，使用模拟数据进行测试
							console.log('使用模拟数据进行测试');
							// this.loadMockData(type);
						}
					})
					.catch(err => {
						console.error('API 调用失败:', err);
						console.error('错误详情:', JSON.stringify(err));
						this.$u.toast('加载数据失败');
						this.loadStatus = 'loadmore';

						// API 调用失败时，使用模拟数据
						console.log('API 调用失败，使用模拟数据');
						// this.loadMockData(type);
					});

				// 临时使用模拟数据
				// const mockData = this.getMockData();

				// if (type === 'refresh') {
				// 	this.giftList = mockData;
				// } else if (type === 'loadmore') {
				// 	this.giftList = this.giftList.concat(mockData);
				// }

				// // 模拟加载状态
				// if (this.query.pageNo >= 3) {
				// 	this.loadStatus = 'nomore';
				// } else {
				// 	this.loadStatus = 'loadmore';
				// }
			},

			
			// 下拉刷新
			refresherrefresh() {
				this.triggered = true;
				this.query.pageNo = 1;
				
				setTimeout(() => {
					this.loadGiftList('refresh');
					this.triggered = false;
					this.$u.toast('刷新成功');
				}, 1000);
			},
			
			// 上拉加载更多
			loadMore() {
				if (this.loadStatus === 'nomore') return;
				
				this.loadStatus = 'loading';
				this.query.pageNo += 1;
				
				setTimeout(() => {
					this.loadGiftList('loadmore');
				}, 500);
			},

			// 测试网络连接
			testNetworkConnection() {
				console.log('开始测试网络连接...');
				console.log('baseUrl:', this.vuex_config ? this.vuex_config.baseUrl : '未配置');
				console.log('token:', this.vuex_token ? '已设置' : '未设置');

				// 测试一个简单的 API 调用
				if (this.$u && this.$u.api && this.$u.api.authInfo) {
					this.$u.api.authInfo()
						.then(res => {
							console.log('网络连接测试成功:', res);
						})
						.catch(err => {
							console.error('网络连接测试失败:', err);
						});
				} else {
					console.error('API 配置不存在');
				}
			},

			// 加载模拟数据（用于测试）
			loadMockData(type = 'refresh') {
				console.log('加载模拟数据，类型:', type);

				const mockData = [
					{
						id: 1,
						iqty: 10,
						amount: 100.00,
						basInv: {
							cinvname: '测试赠品1',
							picUrl: '/static/image/commodity.png'
						}
					},
					{
						id: 2,
						iqty: 5,
						amount: 50.00,
						basInv: {
							cinvname: '测试赠品2',
							picUrl: '/static/image/commodity.png'
						}
					}
				];

				if (type === 'refresh') {
					this.giftList = mockData;
				} else if (type === 'loadmore') {
					this.giftList = this.giftList.concat(mockData);
				}

				this.loadStatus = 'nomore'; // 模拟数据只有一页
				console.log('模拟数据加载完成:', this.giftList);
			},

			// 点击礼品项
			onItemClick(index) {
				return;
				console.log('点击的索引对应的数据:', );

				if (!this.giftList[index]) {
					console.error('礼品项数据为空');
					this.$u.toast('礼品数据异常');
					return;
				}

				// // 可以跳转到礼品详情页
				uni.navigateTo({
				    // url: '/pages/gift/detail?id=' + item.id
					url:'/pagesData/pages/balance-flow/index?id=' + this.giftList[index].id
				});
			},
			search(value) {
				this.giftList = [];
				this.query.pageNo = 1;
				this.query['basInv.cinvname'] = value;
				this.loadGiftList('refresh');
			},
		}
	}
</script>

<style lang="scss" scoped>
	.gift-list-container {
		height: 100vh;
		background: linear-gradient(180deg, #e8e8f5 0%, #f0f0f8 100%);
		display: flex;
		flex-direction: column;
	}

	.header-section {
		background: linear-gradient(180deg, #e8e8f5 0%, #f0f0f8 100%);
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		position: relative;
	}

	.nav-back {
		position: absolute;
		left: 30rpx;
		z-index: 10;
	}

	.u-search-box {
		flex: 1;
		padding: 30rpx 80rpx 50rpx 80rpx;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: #909399;
		margin-left: 10rpx;
	}

	.scroll-list {
		flex: 1;
		height: calc(100vh - 140rpx);
	}

	.list-content {
		margin: 20rpx 30rpx;
		background-color: rgba(255, 255, 255, 0.5);
		border-radius: 20rpx;
		overflow: hidden;
	}
	
	.gift-item {
		background-color: transparent;
		padding: 30rpx;
		display: flex;
		align-items: flex-start;
		position: relative;
		min-height: 140rpx;
	}

	.item-image {
		width: 140rpx;
		height: 140rpx;
		margin-right: 30rpx;
		border-radius: 12rpx;
		overflow: hidden;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.product-image {
		width: 100rpx;
		height: 100rpx;
	}

	.item-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		min-height: 140rpx;
		position: relative;
		// padding-right: 100rpx; /* 为右侧赠品标签预留空间 */
	}

	.product-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		line-height: 1.4;
		margin-bottom: 12rpx;
		word-wrap: break-word;
		word-break: break-all;
		overflow-wrap: break-word;
	}

	.product-desc {
		font-size: 36rpx;
		color: #999;
		margin-bottom: 12rpx;
	}

	.product-price {
		font-size: 36rpx;
		font-weight: 700;
		color: #FF470D;
		margin-top: auto;
	}

	.gift-tag {
		position: absolute;
		// top: 0;
		right: 30rpx;
		bottom: 30rpx;
		background-color: #FF470D;
		border-radius: 30rpx;
		padding: 12rpx 24rpx;
		flex-shrink: 0;
	}

	.tag-text {
		font-size: 24rpx;
		color: #fff;
		font-weight: 500;
	}
	.line {
		height: 1rpx;
		background-color: #ccc;
	}
	.line-wrapper {
		position: absolute;
		bottom: 0;
		left: 30rpx;
		right: 30rpx;
	}
</style>
